import React, { useState } from 'react';
import { Card, Button, Modal, Empty, message, Tooltip, Spin } from 'antd';
import { connect } from 'umi';
import { fetchMailUnbind, fetchSetMainMail } from '@/services/mail';
import _ from 'lodash';
import { MailBindForm } from './components';
import { formatEllipsis } from './utils';
import styles from './styles.less';

const { confirm } = Modal;

// 邮箱管理
const MailManage = ({ mailBindList, dispatch, userCode }) => {
    const [visible, setVisible] = useState(false);
    const [editData, setEditData] = useState({});
    const [operLoading, setOperLoading] = useState(false);

    // 更新绑定信息
    const updateBindInfo = () => {
        dispatch({
            type: 'user/fetchMailBindInfo',
            payload: { userCode }
        });
    };

    // 删除邮箱
    const handleDelete = async e => {
        const { email } = e;
        confirm({
            centered: true,
            title: '确定要删除这个邮箱吗？',
            content: (
                <div style={{ wordWrap: 'break-word', whiteSpace: 'normal', wordBreak: 'break-all' }}>
                    确定删除邮箱账号：{email}里面的邮件都将被清空。
                </div>
            ),
            onOk: async () => {
                // 解绑
                const result = await fetchMailUnbind({
                    userCode,
                    email
                });
                if (result.code === 10000) {
                    message.success('解绑成功');
                    // 如果解绑的邮件是当前前端设置访问的邮箱就删除本地存储
                    if (localStorage.getItem('currentMail') === email) {
                        await localStorage.removeItem('currentMail');
                    }
                    updateBindInfo();
                } else {
                    message.error(result.msg);
                }
            }
        });
    };

    // 设置主邮箱
    const handleSetMainMail = async e => {
        const { email } = e;
        setOperLoading(true);
        const result = await fetchSetMainMail({ email });

        if (result.code === 10000) {
            message.success('设置成功!');
            updateBindInfo();
        } else {
            message.error(result.msg);
        }
        setOperLoading(false);
    };

    return (
        <div>
            <Card
                bordered={false}
                title="邮箱管理"
                style={{ margin: 16 }}
                extra={
                    <div>
                        <span style={{ color: '#BFBFBF', fontSize: 12, fontWeight: 400, marginRight: 16 }}>
                            通过设置其他邮箱账号，可在VV Work邮箱里收取到其他邮箱的邮件
                        </span>
                        <Button
                            type="primary"
                            disabled={_.size(mailBindList) >= 10}
                            onClick={() => {
                                setEditData({});
                                setVisible(true);
                            }}
                        >
                            添加其他邮箱
                        </Button>
                    </div>
                }
            >
                <Spin spinning={operLoading}>
                    <div className={styles.mailManageList}>
                        {_.size(mailBindList) > 0 ? (
                            mailBindList.map(item => (
                                <ul className={item.mainFlag === 1 ? styles.default : ''} key={item.id}>
                                    <li>
                                        {_.size(item.email) > 26 ? (
                                            <Tooltip title={item.email}>
                                                {formatEllipsis(item.email, 26, 12, 11)}
                                            </Tooltip>
                                        ) : (
                                            item.email
                                        )}
                                    </li>
                                    <li>
                                        <Button
                                            type="link"
                                            onClick={() => {
                                                // 设置要编辑的值
                                                const arr = item.email.split('@');
                                                setEditData({
                                                    email: arr[0],
                                                    mailSuffix: `@${arr[1]}`,
                                                    emailPwd: ''
                                                });
                                                setVisible(true);
                                            }}
                                        >
                                            授权
                                        </Button>
                                        <Button
                                            type="link"
                                            disabled={item.mainFlag === 1}
                                            onClick={() => handleSetMainMail(item)}
                                        >
                                            设为默认
                                        </Button>
                                        <Button
                                            type="link"
                                            disabled={item.mainFlag === 1}
                                            onClick={() => handleDelete(item)}
                                        >
                                            删除
                                        </Button>
                                    </li>
                                </ul>
                            ))
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </div>
                </Spin>
            </Card>

            <MailBindForm
                visible={visible}
                data={editData}
                onOk={() => {
                    setVisible(false);
                }}
                onCancel={() => {
                    setVisible(false);
                }}
            />
        </div>
    );
};

export default connect(({ user }) => ({
    userCode: user.currentUser.userCode,
    mailBindList: user.mailBindList
}))(MailManage);
